package com.exmaple.lemlin.ui.abstracts;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.exmaple.lemlin.mvp.base.BasePresenter;
import com.exmaple.lemlin.mvp.base.BaseView;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.trello.rxlifecycle2.components.support.RxFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class AbstractBaseFragment<P extends BasePresenter> extends RxFragment implements BaseView {

    Unbinder unbinder;

    public P mPresenter;

    private View mView = null;
    private Boolean isLazyLoad = false, isCreateView = false, isVisible = false;

    protected abstract int getLayoutId();

    protected abstract void initView();

    protected abstract void initPresenter();

    protected abstract void initLazyLoad();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(getLayoutId(), container, (false));
            isCreateView = true;
        }
        unbinder = ButterKnife.bind((this), mView);
        return mView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initPresenter();

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            onVisible();
        } else {
            onInvisible();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    @Override
    public void onSuccess() {

    }

    @Override
    public void onHint(String hint) {

    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return bindUntilEvent(FragmentEvent.STOP);
    }


    private void onVisible() {

        isVisible = true;

        if (isLazyLoad) {
            onRefreshLoad();
        }
        if (!isLazyLoad && isCreateView && getUserVisibleHint()) {
            isLazyLoad = true;
            initLazyLoad();
        }
    }

    private void onInvisible() {
        isVisible = false;
    }

    public void onRefreshLoad() {
    }
}
